#include "qtmain.h"

#include <QtDebug>
#include <QKeyEvent>
#include <QValidator>

#include "ui_qtmain.h"

QtMain::QtMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::QtMain)
{
    ui->setupUi(this);
    ui->KeyWordInput->setValidator(new QIntValidator(0, 999999, this));
    ui->KeyWordInput->setToolTip(tr("输入数字"));
}

QtMain::~QtMain()
{
    delete ui;
}
const char *uidString = "HAC02";
void QtMain::on_pushButton_clicked()
{
    const char *pUID = uidString;

    ui->passwordOutput->clear();

    if (ui->KeyWordInput->text().isEmpty()) {
        ui->statusbar->showMessage("口令不能为空", 5000);
        return;
    }
    if (ui->KeyWordInput->text().length() != 6) {
        ui->statusbar->showMessage("口令长度必须6位", 5000);
        return;
    }

    qDebug() << "pUID" << pUID;
    qDebug() << "input" << ui->KeyWordInput->text();

    uint32_t inputValue = ui->KeyWordInput->text().toUInt();

    qDebug() << "value" << inputValue;

    char keyBuff[4] = { 0 };
    char pCustomID[4] = { 0 };
    memcpy(pCustomID, &inputValue, 4);
    keyBuff[0] = ((pUID[0] & pCustomID[1]) ^ pCustomID[2]) ^ pCustomID[3];
    keyBuff[1] = (pCustomID[1] ^ (pUID[1] & pCustomID[3])) ^ pCustomID[0];
    keyBuff[2] = (pCustomID[2] | (pCustomID[1] ^ pUID[2])) | pCustomID[3];
    keyBuff[3] = (pCustomID[3] ^ pCustomID[1]) | (pCustomID[0] ^ pUID[3]);
    *((uint32_t *)keyBuff) %= 1000000;
    qDebug() << "keyBuffvalue:" << *((uint32_t *)keyBuff);
    ui->passwordOutput->setText(QString("%1").arg(*((uint32_t *)keyBuff), 6, 10, QLatin1Char('0')));
}

void QtMain::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape) {
        this->close();
    }
}
